const Minio = require('minio');
const { MINIOCONFIG } = require('../database/config');
class MinioUtils {
  // 上传文件
  async uploadFileMinio(fileName, filePath) {
    try {
      console.log('上传文件到minio', fileName, filePath);
      //基本配置
      const minioClient = new Minio.Client(MINIOCONFIG);
      let isExist = await minioClient.bucketExists(MINIOCONFIG.bucketName);
      let err = '';
      if (!isExist) {
        //创建桶后，需要在管理界面修改public访问权限，默认是private
        err = await minioClient.makeBucket(MINIOCONFIG.bucketName, 'cn-north-1');
        return {
          code: 1,
          success: false,
          msg: err,
        };
      }

      if (!err) {
        //上传文件
        const data = await minioClient.fPutObject(MINIOCONFIG.bucketName, fileName, filePath);
        console.log('返回给前端的文件路径>>>', data, `${MINIOCONFIG.endPoint}:${MINIOCONFIG.port}/${MINIOCONFIG.bucketName}/${fileName}`);

        // 删除文件
        // await minioClient.removeObject(MINIOCONFIG.bucketName, fileName); // minio 删除文件
        // fs.unlinkSync(filePath);

        return {
          errcode: 0,
          success: true,
          msg: '上传成功',
          data: `http://${MINIOCONFIG.endPoint}:${MINIOCONFIG.port}/${MINIOCONFIG.bucketName}/${fileName}`,
        };
      }
    } catch (error) {
      return {
        errcode: 1,
        success: false,
        msg: error,
      };
    }
  }
  // 删除文件
  async deleteFileMinio(fileName) {
    try {
      await minioClient.removeObject(MINIOCONFIG.bucketName, fileName); // minio 删除文件
      return {
        errcode: 0,
        success: true,
        msg: '删除成功',
      };
    } catch (error) {
      return {
        errcode: 1,
        success: false,
        msg: error,
      };
    }
  }
}

module.exports = new MinioUtils();
